<?php
namespace App\Service\RegionService;

use App\Model\PssModel\Area;
use App\Service\BaseService;
use App\Model\PssModel\TemplateArea;
use App\Service\Code\Normal;
use Hyperf\Task\Annotation\Task;

/**
 * 省市区全区域列表查询服务
 * @author chenshubo
 */
class RegionService extends BaseService
{  
    const CACHE_REGION_KEY = 'CACHE_REGION_KEY';
    
    /**
     * @Task
     * 查询省市区列表数据服务
     * @param array $param
     */
    public function queryRegionListBySearch( array $param = [] )
    {
        $where = [];
        if( isset($param['pid']) && $param['pid'] !== '' ) {
            $where['pid'] = (int)$param['pid'];
        }
        
        if( !empty($param['name']) ) {
            $where['name'] = $param['name'];
        }
        
        //是否支持树形结构返回
        $is_tree = isset($param['is_tree']) && $param['is_tree'] == 1 ? true : false ; 
        
        $pid = (int)($param['pid'] ??0) ;
        
        //加入缓存
        $parseWhereKey = sha1(json_encode(array_merge($where,['is_tree'=>$is_tree]),JSON_UNESCAPED_UNICODE));
        $redis = redis();        
        $cache_value = $redis->Hget(self::CACHE_REGION_KEY,$parseWhereKey);
        $list = json_decode($cache_value,true);
        
        if( empty($list) )
        {
            $list = Area::instance()->rows($where,['area_id as id','area_name as name','area_parent_id as pid']);
            if( $is_tree ) {
                $list = tree($list,$pid, 'id','pid');
            }
            $json_value = json_encode($list,JSON_UNESCAPED_UNICODE);
            $redis->Hset(self::CACHE_REGION_KEY,$parseWhereKey,$json_value);
        }
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'RegionList' => $list,
            'RegionKey' => $parseWhereKey
        ]);
    }

    /**
     * @Task
     * 查询省市区列表数据根据地址,没有的要自动添加
     * 注意事项：用此接口的前提必须要经过高德地图解析一次，否则不能直接使用，直接使用会导致很多无效数据
     * @param array $param
     */
    public function queryRegionHasParsedByGaoDeAddress(array $param = [])
    {
        if ( empty($param['province']) ) {
            return Normal::returnCode(Normal::FAIL, "缺少province参数");
        }
        
        if ( empty($param['city']) ) {
            return Normal::returnCode(Normal::FAIL, "缺少city参数");
        }
        
        if ( empty($param['district']) ) {
            return Normal::returnCode(Normal::FAIL, "缺少district参数");
        }

        $param['province'] = $this->getProvince($param['province']);

        //获取全部的地区
        $result_query = $this->queryRegionListBySearch(['is_tree'=>1]);
        if( $result_query['code'] != Normal::SUC ) {
            return $result_query;
        }
        
        $RegionCacheKey     = $result_query['data']['RegionKey'];
        $RegionCacheData    = $result_query['data']['RegionList'];
        $regionList         = array_column($RegionCacheData, NULL, 'name');
        
        //获取不到省份直接返回
        if (!isset($regionList[$param['province']])) {
            return Normal::returnCode(Normal::FAIL, "获取服务收货地址省份解析异常，请联系管理员");
        }
        
        $provinceInfo = $regionList[$param['province']];
        $province_id  = $provinceInfo['id'];
        $cityList     = array_column($provinceInfo['list'], NULL, 'name');
        $city_id      = 0;
        $district_id  = 0;
        if( !empty($cityList[$param['city']]) ) 
        {
            $cityInfo = $cityList[$param['city']];
            $districtList  = array_column($cityInfo['list'], NULL, 'name');
            if (!empty($districtList[$param['district']])) 
            {
                $district_id = $districtList[$param['district']]['id'];
            }
        }
        return Normal::returnCode(Normal::SUC, '获取成功', [
            'province_id'   => $province_id,
            'city_id'       => $city_id,
            'district_id'   => $district_id,
        ]);
        
        //以下逻辑已经废弃
        /* try {
            
            //实例化redis
            $redis = redis();
            
            //获取不到城市就,添加城市和区县数据
            if (empty($cityList[$param['city']])) 
            {
                //添加城市
                $city_id = Area::instance()->add([
                    'area_name' => $param['city'],
                    'area_parent_id' => $provinceInfo['id'],
                    'area_deep' =>2,
                    'md' => time(),
                ]);
                
                //添加区县
                $district_id = Area::instance()->add([
                    'area_name' => $param['district'],
                    'area_parent_id' => $city_id,
                    'area_deep' =>3,
                    'md' => time(),
                ]);
                
                //删除已存在的缓存
                $redis->hDel(self::CACHE_REGION_KEY,$RegionCacheKey);
                return Normal::returnCode(Normal::SUC, '获取成功', [
                    'province_id'   => $province_id,
                    'city_id'       => $city_id,
                    'district_id'   => $district_id,
                ]);
            }
            
            $cityInfo       = $cityList[$param['city']];
            $city_id        = $cityInfo['id'];
            $districtList   = array_column($cityInfo['list'], NULL, 'name');
            
            //获取不到区县就,添加区县数据
            if (empty($districtList[$param['district']])) 
            {
                //添加区县
                $district_id = TemplateArea::instance()->add([
                    'name'  => $param['district'],
                    'pid'   => $city_id,
                    'cd'    => time(),
                ]);
                
                //删除已存在的缓存
                $redis->hDel(self::CACHE_REGION_KEY,$RegionCacheKey);
            } else {
                $district_id = $districtList[$param['district']]['id'];
            }
            
            return Normal::returnCode(Normal::SUC, '获取成功', [
                'province_id'   => $province_id,
                'city_id'       => $city_id,
                'district_id'   => $district_id,
            ]);
        } catch ( \Throwable $th) {
            //删除已存在的缓存
            $redis->hDel(self::CACHE_REGION_KEY,$RegionCacheKey);
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍后再试【{$th->getMessage()},{$th->getLine()}】");
        } */
    }
    
    /**
     * 处理省份问题
     * @param string $province
     * @return string|\App\Service\RegionService\string
     */
    private function getProvince(string $province)
    {
        //判断直辖市
        if(in_array($province,['天津','北京','上海','重庆'])){
            return $province .'市';
        }
        
        //判断是否缺失省份，并且排除直辖市
        if( mb_strlen($province,'utf8') == 2 && !in_array($province,['北京','上海','重庆','天津']) ) {
            return $province.'省';
        }
        
        //判断是否黑龙江
        if( $province == '黑龙江' ) {
            return $province.'省';
        }
        
        //判断是否自治区
        if(in_array($province,['内蒙古','新疆维吾尔','西藏','广西壮族'])){
            return $province .'自治区';
        }
        
        //判断是否特别行政区
        if(in_array($province,['香港','澳门'])){
            return $province .'特别行政区';
        }
        
        return $province;
    }
}